use prettytable::{Attr, Cell, Row, Table};

use crate::config::{Config, Service};

pub trait ServerUtils {
    fn print_logo(&self);
    fn print_table(&self);
    fn server_url(&self) -> String;
    fn generate_index_html(&self) -> String;
}

impl ServerUtils for Config {
    /// print the logo of ours
    fn print_logo(&self) {
        println!(include_str!("../../public/logo.txt"));
        println!("VERSION: {}", "0.1.0");
        println!("Service is running at http://{}", self.server_url());
    }

    fn print_table(&self) {
        let mut table = Table::new();
        table.add_row(Row::new(vec![
            Cell::new("name").with_style(Attr::Bold),
            Cell::new("file").with_style(Attr::Bold),
            Cell::new("url").with_style(Attr::Bold),
            Cell::new("description").with_style(Attr::Bold),
        ]));

        for s in &self.services {
            table.add_row(Row::new(vec![
                Cell::new(&s.name),
                Cell::new(&s.file),
                Cell::new(&s.url),
                Cell::new(&s.desp),
            ]));
        }

        table.printstd();
        println!("");
    }

    fn generate_index_html(&self) -> String {
        let welcome = self
            .services
            .iter()
            .map(
                |Service {
                     name, desp, url, ..
                 }| {
                    format!(include_str!("../../public/table.html"), name, desp, url)
                },
            )
            .collect::<Vec<String>>()
            .join("\n");
        format!(include_str!("../../public/index.html"), self.title, welcome,)
    }

    fn server_url(&self) -> String {
        format!("localhost:{}", self.port)
    }
}
